import { type NextRequest, NextResponse } from "next/server"
import { v4 as uuidv4 } from "uuid"
import { getDb } from "@/lib/db-sqlite"

// 添加评论
export async function POST(request: NextRequest, { params }: { params: { id: string } }) {
  try {
    // 正确处理 params
    const { id: pollId } = await params
    const { text } = await request.json()

    if (!text) {
      return NextResponse.json({ error: "Invalid data" }, { status: 400 })
    }

    const db = getDb()

    // 检查投票是否存在
    const poll = db
      .prepare(`
      SELECT * FROM polls
      WHERE id = ?
    `)
      .get(pollId)

    if (!poll) {
      return NextResponse.json({ error: "Poll not found" }, { status: 404 })
    }

    // 添加评论
    const commentId = uuidv4()
    const now = new Date().toISOString()

    db.prepare(`
      INSERT INTO comments (id, poll_id, text, created_at)
      VALUES (?, ?, ?, ?)
    `).run(commentId, pollId, text, now)

    // 获取创建的评论
    const comment = db
      .prepare(`
      SELECT * FROM comments
      WHERE id = ?
    `)
      .get(commentId)

    return NextResponse.json({ comment })
  } catch (error: any) {
    console.error("Error adding comment:", error)
    return NextResponse.json({ error: error.message || "Failed to add comment" }, { status: 500 })
  }
}
